<?php
declare (strict_types = 1);

namespace app\admin\middleware;

use think\facade\View;
use app\admin\service\AdminService;

class Auth
{
    /**
     * 处理请求
     *
     * @param \think\Request $request
     * @param \Closure       $next
     * @return Response
     */
    public function handle($request, \Closure $next)
    {
        //
        $user_id = session('user_id');
        if(!$user_id){
            return redirect('/admin/login');
        }
        $adminService = new AdminService();

        $menus = $adminService->getMenuList($user_id);
        if(empty($menus)){
            return redirect('/admin/login');
        }  

        $result = $this->checkPermission($menus);
        $request->allowed = $result;
        
        // 生成菜单
        $data = generateTree($menus);

        View::assign('menus',$data);
        
        return $next($request);
    }

    // 检查用户权限
    protected function checkPermission($menus)
    {   
        $rule = array_column($menus,'node');
        $currentRule = app('http')->getName() . '@' . request()->controller(true) . '@' . request()->action(true);
        //halt($currentRule);
        $result = in_array($currentRule,$rule);

        return  $result;
    }

}
